﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using System.ComponentModel;
using it_security_project.App_Code.BusinessLogicLayer;
using it_security_project.App_Code;
using System.Text.RegularExpressions;
//using SecurePages.Infrastructure;
//using SecurePages.TestHelpers;

namespace it_security_project
{
    public partial class Login : System.Web.UI.Page
    {
        private string ValidationGroup = "loginvalidation";

        public new Site site { get { return base.Master as Site; } }

        protected override void OnInit(EventArgs e)
        {
            Service service = new Service();
            if (!service.IsBanned(Request.ServerVariables["REMOTE_ADDR"], DateTime.Now.Ticks.ToString()))
            {
                Member member = site.LoginWithSession();

                if (member != null) // User is NOT logged in
                {
                    Response.Redirect("~/Default.aspx");
                }

                if (Request.QueryString["message"] != null)
                {
                    if (Request.QueryString["message"].ToString() == "registersuccess")
                    {
                        site.ChangeCustomMessage("Registration was completed, you can now login!", MessageType.Success);
                    }
                }
            }
            else
            {
                site.ChangeCustomMessage("You are temporary banned", MessageType.Error);
                PlaceHolderLogin.Visible = false;
            }
            
            
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if(ValidateInput()){
                var Username = UserTextBox.Text;
                var Password = PasswordTextBox.Text;
               
                var member = site.LoginUserWithInput(Username, Password);

                if (member != null)
                {
                    var ID = Convert.ToInt64(member.MemberID);

                    site.SetViewstate(member);

                    if (member.Role == Roles.Member)
                    {
                        Response.Redirect("~/Profile.aspx");
                    }
                    else if (member.Role == Roles.Admin)
                    {
                        Response.Redirect("~/Profile.aspx");
                    }
                    else
                    {
                        Response.Redirect("~/Error.aspx");
                    }
                }
                else
                {                   
                    PageExtensions.AddErrorMessage(this, "Invalid username or password", ValidationGroup);
                }
            }
            else
            {
                
                if (ViewState["attemts"] != null)
                {
                    if (int.Parse(ViewState["attemts"].ToString()) >= 3)
                    {
                        PageExtensions.AddErrorMessage(this, "3 or more unsuccessful login attempts detected!", ValidationGroup);

                        Service service = new Service();
                        var UserIPAddress = Request.ServerVariables["REMOTE_ADDR"];
                        var ticks = DateTime.Now.AddMinutes(1).Ticks;
                        service.addBan(UserIPAddress, ticks);                       
                    }
                    else
                    {
                        ViewState["attemts"] = int.Parse(ViewState["attemts"].ToString()) + 1;
                    }
                }
                else
                {
                    ViewState["attemts"] = 1;
                }                
            }
        }

        private bool ValidateInput()
        {
            Regex regex = new Regex("[`´;]");

            var Username = UserTextBox.Text;
            var Password = PasswordTextBox.Text;
            if (Username == "")
            {
                PageExtensions.AddErrorMessage(this, "Enter a username", ValidationGroup);
                return false;
            }
            if (Password == "")
            {
                PageExtensions.AddErrorMessage(this, "Enter a password", ValidationGroup);
                return false;
            }
            // Check if user enters ´;
            if (regex.IsMatch(Username) || regex.IsMatch(Password))
            {
                PageExtensions.AddErrorMessage(this, "Invalid username or password", ValidationGroup);
                return false;
            }
            if (Username.Length > 50)
            {
                PageExtensions.AddErrorMessage(this, "Invalid username or password", ValidationGroup);
                return false;
            }
            if (Password.Length > 50)
            {
                PageExtensions.AddErrorMessage(this, "Invalid username or password", ValidationGroup);
                return false;
            }

            // All validation is ok
            return true;
        }
    }
}